package com.caineng.zhaobiao.zbapi.interceptor;

import cn.dev33.satoken.exception.NotLoginException;
import com.caineng.zhaobiao.zbapi.utils.AjaxResult;
import com.caineng.zhaobiao.zbapi.utils.email.MyEmailBean;
import com.caineng.zhaobiao.zbapi.utils.email.MyEmailUtil;
import com.caineng.zhaobiao.zbapi.utils.ip.AddressUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理器
 */
@Slf4j
@RestControllerAdvice // 控制器增强处理(返回 JSON 格式数据)，添加了这个注解的类能被 classpath 扫描自动发现
public class ExceptionHandle {

    @Autowired
    MyEmailUtil myEmailUtil;

    @ExceptionHandler(value = Exception.class) // 捕获 Controller 中抛出的指定类型的异常，也可以指定其他异常
    public AjaxResult handler(Exception exception, HttpServletRequest request){

        int port = request.getLocalPort();
        String ip = AddressUtils.getRealIpAddr(request);

        String address =  AddressUtils.getRealAddressByIP(ip);//IP 对应的地址

        String path = request.getServletPath()+request.getRequestURI();
        if (exception instanceof NotLoginException){
            log.error(port+"token错误"+path+" "+ip+" address"+address);
            AjaxResult res = AjaxResult.error("请先登录");
            res.setCode("401"); //没有权限
            return res;
        } else {
            String message = exception.getMessage()+"    "+path+" "+ip+" address: "+address ;
            myEmailUtil.sendSimpleMail(new MyEmailBean("2840402853@qq.com","zbapi-SpringBoot报错",message));
            log.error(port+"异常报错"+path+" "+ip+" address"+address,exception);
            return AjaxResult.error("对不起，操作错误，请联系平台管理员!");
        }
    }
}